using UnityEngine;
using LitJson;
using System.Collections.Generic;
using UnityEngine.Networking;
#if UNITY_WEBGL
using System.Runtime.InteropServices;
#endif

namespace CGF
{
    public class GetPhotoWeb : MonoBehaviour
    {
#if UNITY_WEBGL
        // 导入原生插件中的函数
        [DllImport("__Internal")]
        private static extern void OpenPhotoPicker(int allowMultiSelect);
        [DllImport("__Internal")]
        private static extern void RevokeObjectURL(string url);
        [DllImport("__Internal")]
        private static extern void RefreshFocus();
#endif

        private CTask<string[]> task;

        // 单例模式（可选但推荐，用于接收回调）
        private static GetPhotoWeb _instance;
        public static GetPhotoWeb Instance
        {
            get
            {
                if (!_instance)
                {
                    _instance = GameObject.FindObjectOfType<GetPhotoWeb>();
                    if (!_instance)
                    {
                        GameObject go = new GameObject(nameof(GetPhotoWeb));
                        _instance = go.AddComponent<GetPhotoWeb>();
                        DontDestroyOnLoad(go);
                    }
                }
                return _instance;
            }
        }

        public async CTask<string[]> _GetPhotoFromAlbum(bool allowMultiSelect)
        {
            task = CTask<string[]>.Create();
#if UNITY_WEBGL
            OpenPhotoPicker(allowMultiSelect ? 1 : 0);
#endif
            return await task;
        }

        public async CTask<Texture2D> _GetTextureByPath(string path)
        {
            UnityWebRequest request = UnityWebRequestTexture.GetTexture(path);
            await request.SendWebRequest();
            if (request.result != UnityWebRequest.Result.Success || request.error != null)
            {
                Debug.LogError($"加载图片失败: {request.error}");
                return null;
            }
            Texture2D texture = DownloadHandlerTexture.GetContent(request);
#if UNITY_WEBGL
            RevokeObjectURL(path);
            RefreshFocus();
#endif
            return texture;
        }

        // 用于接收原生回调的MonoBehaviour方法，使用public防止被混淆
        public void _OnPhotoPickedCallback(string json)
        {
            Debug.Log($"json: {json}");
            if (string.IsNullOrEmpty(json))
            {
                task.SetResult(null);
                return;
            }
            List<string> paths = new List<string>();
            JsonData jsonData = JsonMapper.ToObject(json);
            for (int i = 0; i < jsonData.Count; i++)
            {
                paths.Add(jsonData[i]["url"].ToString());
            }
            task.SetResult(paths.ToArray());
        }
    }
}
